﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Prism.MefExtensions;
using System.Windows;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;

namespace Codeplex.KinkumaFramework
{
    public class KinkumaBootstrapper<TShell> : MefBootstrapper
        where TShell : DependencyObject
    {
        private static KinkumaBootstrapper<TShell> instance;

        private static Func<KinkumaBootstrapper<TShell>> factory = () => new KinkumaBootstrapper<TShell>();

        public static KinkumaBootstrapper<TShell> Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = factory();
                }

                return instance;
            }
        }

        public static void SetInstanceFactory(Func<KinkumaBootstrapper<TShell>> f)
        {
            if (f == null)
            {
                throw new ArgumentNullException("f");
            }

            factory = f;
        }

        protected KinkumaBootstrapper()
        {
        }

        protected override void ConfigureContainer()
        {
            base.ConfigureContainer();
            ContainerHolder.Container = this.Container;
        }

        protected override DependencyObject CreateShell()
        {
            return this.Container.GetExportedValue<TShell>();
        }

        protected override void InitializeShell()
        {
            base.InitializeShell();
#if !SILVERLIGHT
            Application.Current.MainWindow = this.Shell as Window;
            Application.Current.MainWindow.Show();
#else
            Application.Current.RootVisual = this.Shell as UIElement;
#endif
        }

        protected override void ConfigureAggregateCatalog()
        {
            base.ConfigureAggregateCatalog();
            this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(TShell).Assembly));
#if !SILVERLIGHT
            this.AggregateCatalog.Catalogs.Add(
                new DirectoryCatalog(".", "*.Module.dll"));
#endif
        }
    }
}
